use anyhow::Result;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use crate::REQWEST_CLIENT;
/// 基本概况
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct FundJbgk {
    pub full_name: String,                 // 基金全称
    pub short_name: String,                // 基金简称
    pub fund_code: String,                 // 基金代码
    pub fund_type: String,                 // 基金类型
    pub issue_date: String,                // 发行日期
    pub establishment_date_size: String,   // 成立日期/规模
    pub asset_size: String,                // 资产规模
    pub share_size: String,                // 份额规模
    pub fund_manager: String,              // 基金管理人
    pub fund_custodian: String,            // 基金托管人
    pub fund_manager_personnel: String,    // 基金经理人
    pub dividend_since_inception: String,  // 成立来分红
    pub management_fee_rate: String,       // 管理费率
    pub custodian_fee_rate: String,        // 托管费率
    pub sales_service_fee_rate: String,    // 销售服务费率
    pub max_subscription_fee_rate: String, // 最高认购费率
    pub max_purchase_fee_rate: String,     // 最高申购费率
    pub max_redemption_fee_rate: String,   // 最高赎回费率
    pub performance_benchmark: String,     // 业绩比较基准
    pub tracking_target: String,           // 跟踪标的

    pub investment_objective: String,        // 投资目标
    pub investment_philosophy: String,       // 投资理念
    pub investment_scope: String,            // 投资范围
    pub investment_strategy: String,         // 投资策略
    pub dividend_policy: String,             // 分红政策
    pub risk_return_characteristics: String, // 风险收益特征
}

impl FundJbgk {
    /// Refer to: https://fundf10.eastmoney.com/jbgk_159001.html 基本概况
    ///
    /// code: e.g. 159001
    pub async fn fund_jbgk(code: &str) -> Result<FundJbgk> {
        // GET /jbgk_159001.html HTTP/1.1
        // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
        // Accept-Encoding: gzip, deflate, br
        // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
        // Cache-Control: no-cache
        // Connection: keep-alive
        // Cookie: qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; ASP.NET_SessionId=5ufgex2sjbo4p44lwytenq3s; searchbar_code=159834; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND1=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND2=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND3=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND4=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND5=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND6=02-02%2010%3A30%3A22@%23%24%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; EMFUND7=02-26%2016%3A07%3A01@%23%24%u91D1%u9E70%u6DFB%u76C8%u7EAF%u503A%u503A%u5238A@%23%24003384; EMFUND8=02-27%2010%3A51%3A37@%23%24%u534E%u590F%u6210%u957F%u6DF7%u5408@%23%24000001; EMFUND9=02-27 13:53:07@#$%u534E%u6CF0%u67CF%u745E%u5357%u65B9%u4E1C%u82F1%u6052%u751F%u79D1%u6280%28QDII-ETF%29@%23%24513130; st_asi=delete; HAList=ty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-159001-%u8D27%u5E01ETF%2Cty-0-161127-%u6807%u666E%u751F%u7269%u79D1%u6280LOF%2Cty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=992; st_psi=20240229152652284-112200305283-5554982915
        // Host: fundf10.eastmoney.com
        // Pragma: no-cache
        // Sec-Fetch-Dest: document
        // Sec-Fetch-Mode: navigate
        // Sec-Fetch-Site: none
        // Sec-Fetch-User: ?1
        // Upgrade-Insecure-Requests: 1
        // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
        // sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"
        // sec-ch-ua-mobile: ?0
        // sec-ch-ua-platform: "macOS"

        let request_url = format!("https://fundf10.eastmoney.com/jbgk_{code}.html");
        let response = REQWEST_CLIENT.get(request_url)
        .header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
        .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
        .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
        .header(reqwest::header::CACHE_CONTROL,"no-cache")
        .header(reqwest::header::CONNECTION,"keep-alive")
        // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
        .header(reqwest::header::HOST,"fundf10.eastmoney.com")
        .header(reqwest::header::PRAGMA, "no-cache")
        // .header(reqwest::header::REFERER , "https://fundf10.eastmoney.com/cyrjg_000001.html")
        .header(reqwest::header::USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
        .header("Sec-Ch-Ua", "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"")
        .header("Sec-Ch-Ua-Mobile", "?0")
        .header("Sec-Ch-Ua-Platform", "\"macOS\"")
        .header("Sec-Fetch-Dest", "empty")
        .header("Sec-Fetch-Mode", "cors")
        .header("Sec-Fetch-Site", "same-origin")
        .send()
        .await?;

        let body = response.text().await?;
        // println!("body: {:?}", body);

        let fund_jbgk = Self::extract_data(&body)?;

        Ok(fund_jbgk)
    }

    fn extract_data(html: &str) -> Result<FundJbgk> {
        let mut fund_jbgk = FundJbgk {
            ..Default::default()
        };
        // println!("\n\nfund_cyrbd_list content={}", self.content);
        let document = Html::parse_document(html);
        let table_selector = Selector::parse("table.info.w790 tbody tr")
            .map_err(|e| anyhow::anyhow!(e.to_string()))?;
        let td_selector = &Selector::parse("td").map_err(|e| anyhow::anyhow!(e.to_string()))?;
        // <tr><th>基金全称</th><td style="width:300px;padding-right:10px;">易方达保证金收益货币市场基金</td><th>基金简称</th><td>易方达保证金货币A</td></tr>

        for (index, row) in document.select(&table_selector).enumerate() {
            if index == 0 {
                fund_jbgk.full_name = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.short_name = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 1 {
                fund_jbgk.fund_code = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.fund_type = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 2 {
                fund_jbgk.issue_date = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.establishment_date_size = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 3 {
                fund_jbgk.asset_size = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.share_size = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 4 {
                fund_jbgk.fund_manager = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.fund_custodian = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 5 {
                fund_jbgk.fund_manager_personnel = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.dividend_since_inception = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 6 {
                fund_jbgk.management_fee_rate = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.custodian_fee_rate = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 7 {
                fund_jbgk.sales_service_fee_rate = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.max_subscription_fee_rate = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 8 {
                fund_jbgk.max_purchase_fee_rate = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.max_redemption_fee_rate = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            } else if index == 9 {
                fund_jbgk.performance_benchmark = row
                    .select(td_selector)
                    .nth(0)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();

                fund_jbgk.tracking_target = row
                    .select(td_selector)
                    .nth(1)
                    .map(|td| td.text().collect::<String>())
                    .unwrap_or_default();
            }
        }

        // Define a CSS selector to select the parent <div> elements
        let div_selector =
            Selector::parse("div.boxitem.w790").expect("Failed to parse parent div selector");

        for div in document.select(&div_selector) {
            // pub investment_objective: String,        // 投资目标
            // Check if the text of any child label contains "投资目标"

            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("投资目标")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.investment_objective = text.replace("\n", "").replace(" ", "");
            }

            // pub investment_philosophy: String,       // 投资理念
            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("投资理念")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.investment_philosophy = text.replace("\n", "").replace(" ", "");
            }

            // pub investment_scope: String,            // 投资范围
            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("投资范围")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.investment_scope = text.replace("\n", "").replace(" ", "");
            }

            // pub investment_strategy: String,         // 投资策略

            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("投资策略")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.investment_strategy = text.replace("\n", "").replace(" ", "");
            }
            // pub dividend_policy: String,             // 分红政策
            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("分红政策")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.dividend_policy = text.replace("\n", "").replace(" ", "");
            }
            // pub risk_return_characteristics: String, // 风险收益特征
            let target_text = div
                .select(&Selector::parse("label.left").unwrap())
                .find(|label| label.text().any(|text| text.contains("风险收益特征")))
                .map(|_label| div.text().collect::<String>());
            if let Some(text) = target_text {
                fund_jbgk.risk_return_characteristics = text.replace("\n", "").replace(" ", "");
            }
        }

        Ok(fund_jbgk)
    }
}

#[cfg(test)]
mod test {
    use crate::fund::fund_jbgk::FundJbgk;

    #[tokio::test]
    async fn test_fund_jbgk() {
        let result = FundJbgk::fund_jbgk("000001").await;

        // println!("result={:?}", result);

        assert_eq!(result.is_ok(), true);
        if let Ok(fund_jbgk) = result {
            println!("fund_jbgk= {:?}\n", fund_jbgk);
        }
    }
}
